import React, {FC, useContext, useState} from 'react';
import "./index.less";
import {Checkbox, Col, Row} from 'antd';
import {SearchPageContext} from "@/pages/SearchPage/common/SearchPageContext";
import {history} from "@@/core/history";
import queryString from "query-string";
import lodash from "lodash";
import usePgSearch from "@/pages/SearchPage/common/usePgSearch";


export interface EsAgg {
  key: string;
  displayName?: string;
  icon?: React.ReactNode;
  docCount: number;
}

interface EsSearchFilterPartProps {
  fieldName: string;
  title: React.ReactNode;
  icon?: React.ReactNode;
  options: EsAgg[];
}

/**
 * EsSearchFilterPart 页面
 */
const EsSearchFilterPart: FC<EsSearchFilterPartProps> = (props) => {
  const {fieldName, icon, title, options} = props;
  const {currentSearch} = usePgSearch()

  if (!options || options.length == 0) {
    return null;
  }

  let value: string[] = [];
  if (currentSearch?.[fieldName]) {
    if (lodash.isArray(currentSearch?.[fieldName])) {
      value = currentSearch?.[fieldName] as string[];
    } else {
      value = [currentSearch?.[fieldName]] as string[];
    }
  }


  console.log("value",value,fieldName)

  return (
    <div className={"es-search-filter-part-container"}>
      <div className={"es-search-filter-part-header"}>
        {icon && <div className={"es-search-filter-part-icon"}>{icon}</div>}
        <div className={"es-search-filter-part-title"}>{title}</div>
      </div>
      <div className={"es-search-filter-part-content"}>
        <Checkbox.Group value={value} onChange={(val) => {
          history.push({
            pathname: ``,
            search: queryString.stringify({
              ...currentSearch,
              [fieldName]: val
            })
          });
        }}>
          <Row gutter={[16, 16]}>
            {options.map((option) => {
              return (
                <Col key={option.key} span={24}>
                  <Checkbox value={option.key}>{option.displayName || option.key} ({option.docCount})</Checkbox>
                </Col>
              )
            })}
          </Row>
        </Checkbox.Group>
      </div>
    </div>
  );
};

export default EsSearchFilterPart;
